from uuid import UUID

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileSize, FileRequired
from internal.entity.upload_entity import ALLOW_DOCUMENT_EXTENSION, ALLOW_IMG_EXTENSION
from marshmallow import fields, pre_dump, Schema
from internal.model import UploadFile


class UploadSchema(FlaskForm):
    file = FileField(
        "file",
        validators=[
            FileRequired("上传文件不能为空"),
            FileSize(max_size=15 * 1024 * 1024, message="文件大小不能超过15MB"),
            FileAllowed(ALLOW_DOCUMENT_EXTENSION, message=f"仅允许上传{ALLOW_DOCUMENT_EXTENSION}格式"),
        ]
    )


class UploadImageSchema(FlaskForm):
    file = FileField(
        "file",
        validators=[
            FileRequired("上传图片不能为空"),
            FileSize(max_size=15 * 1024 * 1024, message="图片大小不能超过15MB"),
            FileAllowed(ALLOW_IMG_EXTENSION, message=f"仅允许上传{ALLOW_IMG_EXTENSION}"),
        ]
    )


class UploadSchemaResp(Schema):
    account_id: UUID = fields.UUID()
    name: str = fields.String(default="")
    key: str = fields.String(default="")
    size: int = fields.Integer(default=0)
    extension: str = fields.String(default="")
    mime_type: str = fields.String(default="")
    hash: str = fields.String(default="")
    created_at: int = fields.Integer(default=0)

    @pre_dump
    def process_data(self, upload_file: UploadFile, **kwargs):
        return {
            "account_id": upload_file.account_id,
            "name": upload_file.name,
            "key": upload_file.key,
            "size": upload_file.size,
            "extension": upload_file.extension,
            "mime_type": upload_file.mime_type,
            "hash": upload_file.hash,
            "created_at": int(upload_file.created_at.timestamp()),
        }
